package com.bangbang.controller;


import com.bangbang.configresult.Result;
import com.bangbang.configresult.ResultEnum;
import com.bangbang.feign.PayServiceFeign;
import com.bangbang.mapper.TbAdvertisingColumnMapper;
import com.bangbang.pojo.TbAdvertising;
import com.bangbang.pojo.TbAdvertisingColumn;
import com.bangbang.pojo.TbAdvertisingOrder;
import com.bangbang.service.ITbAdvertisingColumnService;
import com.bangbang.service.ITbAdvertisingOrderService;
import com.bangbang.service.ITbAdvertisingService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import feign.FeignException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 广告表 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2021-08-14
 */
@RestController
@RequestMapping("/groupCourse/tbAdvertising")
@Api(value = "前台提交广告信息")
public class TbAdvertisingController {

    @Autowired
    private RedisTemplate redisTemplate;

   /* @Autowired
    private RocketMQTemplate rocketMQTemplate;*/

    @Autowired
    private ITbAdvertisingService advertisingService;

    @Autowired
    private ITbAdvertisingColumnService advertisingColumnService;

    @Autowired
    private ITbAdvertisingOrderService advertisingOrderService;

    @Autowired
    private PayServiceFeign payServiceFeign;

    @ApiOperation("定时查询广告/使用方")
    @GetMapping("queryByFieldId")
    public Result query(){
        List<TbAdvertising> advertisingList = advertisingService.queryAdvertiseAtDay();
        return Result.buildResult(ResultEnum.SUCCESS).setResult(advertisingList);
    }

    @ApiOperation("广告cpc计费")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "adv_id", value = "广告id", required = true,paramType = "query"),
            @ApiImplicitParam(name = "adv_billing_id", value = "广告投放方id", required = true,paramType = "query"),
            @ApiImplicitParam(name = "adv_lanwei_classity", value = "广告栏位id", required = true,paramType = "query"),
    })
    @GetMapping("cpc")
    public Result queryAdvertise(@RequestParam("adv_id")Long advId, @RequestParam("adv_billing_id")Long advBillingId,@RequestParam("adv_lanwei_classity")Long fieldId){
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        Boolean key = redisTemplate.hasKey("s"+advId);
        Boolean hkey = redisTemplate.hasKey("h"+advId);
        if(key){
            String num = (String) redisTemplate.opsForValue().get("s"+advId);
            long l = Long.parseLong(num + "");
            if(l<100){
                redisTemplate.opsForValue().increment("s"+advId);
            }else {
                redisTemplate.opsForValue().getAndSet("s"+advId,"0");
                BigDecimal price = (BigDecimal) redisTemplate.opsForValue().get(advId);//用户存入的金额
                BigDecimal divide = price.divide(new BigDecimal("1"));
                redisTemplate.opsForValue().set(advId,divide);
                if(Long.parseLong(price.toString())<=0){
                    //下架该广告
                    redisTemplate.delete("s"+advId);
                    redisTemplate.delete("h"+advId);
                    redisTemplate.delete(advId);
                    redisTemplate.delete(fieldId);
                }
            }
        }
        if (hkey){
            String advUrl = (String) redisTemplate.opsForHash().get("h"+advId,"adv_url");
            return Result.buildResult(ResultEnum.SUCCESS).setResult(advUrl);
        }
        return Result.buildResult(ResultEnum.SUCCESS);
    }



    @ApiOperation("广告投放")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "投放广告信息",name = "advertising", required = true, paramType = "body")
    })
    @PostMapping
    public String selectAdvertise(TbAdvertising advertising){
//        redisTemplate.setValueSerializer(new StringRedisSerializer());
//        Object o1 = redisTemplate.boundValueOps("f8d51ba6-fd96-4e59-9d9e-0a873eed2b9e").get();
//        String s = o1.toString();
//        long l = Long.parseLong(s+ "");
//        advertising.setAdvTeacherId(l);
        //执行支付 发送支付的半消息 本地保存订单
        //rocketMQTemplate.sendMessageInTransaction();
        //查看对应栏位是否有广告存在
        Long fieldId = advertising.getAdvLanweiClassify();
        Boolean hasKey = redisTemplate.hasKey(fieldId);
        if(hasKey){
            return "当前栏位已有广告";
        }
        //生成订单信息
        TbAdvertisingOrder order = new TbAdvertisingOrder();
        order.setOrderPayment(advertising.getAdvPrice());
        order.setOrderTeacherId(advertising.getAdvTeacherId());
        order.setOrderCreateTime(new Date());
        order.setOrderPaymentType(advertising.getAdvBillingId());
        advertisingOrderService.saveResultId(order);
        try {
            advertisingService.insertResultId(advertising);
            Map<String,Object> map = new HashMap<>();
            map.put("adv_url",advertising.getAdvUrl());
            map.put("adv_content",advertising.getAdvContent());
            map.put("adv_commodity_id",advertising.getAdvCommodityId());
            map.put("adv_lanwei_classify",advertising.getAdvLanweiClassify());
            map.put("adv_teacher_id",advertising.getAdvTeacherId());
            map.put("adv_billing_id",advertising.getAdvBillingId());
            Long advId = advertising.getAdvId();
            long time = advertising.getAdvFinishTime().getTime()-advertising.getAdvBeginTime().getTime();
            redisTemplate.opsForValue().set(fieldId,"lock");
            redisTemplate.expire(fieldId,time, TimeUnit.SECONDS);
            redisTemplate.opsForHash().putAll("h"+advertising.getAdvId(),map);
            redisTemplate.expire("h"+advId,time, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set("s"+advertising.getAdvId(),"0");
            redisTemplate.expire("s"+advId,time, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set(advId,advertising.getAdvPrice().toString());
            redisTemplate.expire(advId,time, TimeUnit.SECONDS);
        }catch (Exception e){
            e.printStackTrace();
            return "投放失败，请稍后重试";
        }
        //调用支付接口//
        String result = payServiceFeign.alipayTradePagePay(order.getOrderId(),order.getOrderPayment(),"广告支付","8030");
        System.err.println(result);
        return result;
    }



    @ApiOperation("广告查询/投放方")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "广告栏位ID",name = "col_id", required = true, paramType = "query"),
            @ApiImplicitParam(value = "是否勾选节假日(0、1)",name = "is_holiday", required = true ,paramType = "query")
    })
    @GetMapping
    public Result selectAdvertise(@RequestParam("is_holiday") String isHoliday, @RequestParam("col_id")Long colId){
        List<TbAdvertisingColumn> columnList = advertisingColumnService.queryCol(isHoliday,colId);
        //根据栏位iD查询该栏位下的广告、给投放者展示
        List<TbAdvertising> advertisingList = advertisingService.queryAdvertise(colId);
        Map<String,Object> map = new HashMap<>();
        map.put("advertisingList",advertisingList);
        map.put("columnList",columnList);
        return Result.buildResult(ResultEnum.SUCCESS).setResult(map);
    }


}

